package com.yt.server.mode;

import java.util.Random;

import com.yt.server.mode.api.INotification;
import com.yt.server.mode.patterns.command.Command;
import com.yt.server.mode.patterns.facade.Facade;
import com.yt.server.mode.patterns.proxy.Proxy;

public class Example {

	private static class Command1 extends Command {

		private long i = 0;

		{
			i = System.currentTimeMillis();
		};

		private Command1() {
			super("com1");
		}

		private Command1(String command1) {
			super(command1);
		}

		@Override
		public void handleNotification(INotification notification) {
			System.out.println("控制器被回调了,选取业务执行.");
			String list[] = facade.retrieveProxy("proxy1")
					.listNotificationInterests();
			try {
				Thread.sleep(1000);
				sendNotification(list[new Random().nextInt(list.length)]);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		public void add() {
			sendNotification("add");
		}
	}

	private static class Proxy1 extends Proxy {

		private long i = 0;
		{
			i = System.currentTimeMillis();
		}

		private Proxy1(String proxyName) {
			super(proxyName);
		}

		@Override
		public void handleNotification(INotification notification) {
			System.out.print("业务层被调用了: ");
			String n = notification.getName();
			if ("add" == n) {
				System.out.println("add....");
			} else if ("delete" == n) {
				System.out.println("delete...");
			} else if ("update" == n) {
				System.out.println("update...");
			} else if ("search" == n) {
				System.out.println("search...");
			}
			try {
				Thread.sleep(1000);
				sendNotification("command1", "返回结果");// 返回到控制层
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		@Override
		public String[] listNotificationInterests() {
			return new String[] { "add", "delete", "update", "search" };
		}
	}

	static long s;

	public static void main(String[] args) {
		new Thread(new Runnable() {
			{
				s = System.currentTimeMillis();
			}

			public void run() {
				Facade facade = Facade.getInstance();
				Command1 command1 = new Command1("command1");// 控制器
				Proxy1 proxy1 = new Proxy1("proxy1");// 业务区
				facade.registerCommand(command1);
				facade.registerProxy(proxy1);
				command1.add();
			}
		}).start();
		System.out.println("创建话费时间" + (System.currentTimeMillis() - s));
	}
}